import os
import shutil
from datetime import datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from config.constants import driver_path, chrome_path
from utils.browser_utils import init_chrome_browser


class DatabaseBackupTool:
    """数据库备份工具类 (核心功能)"""

    def __init__(self, download_dir, backup_dir, log_dir='logs'):
        self.download_dir = download_dir
        self.backup_dir = backup_dir
        self.log_dir = log_dir
        self.log_file = os.path.join(log_dir, 'backup.log')
        self._ensure_dirs_exist()
        self.driver = None

    def _ensure_dirs_exist(self):
        """确保所有需要的目录都存在"""
        os.makedirs(self.backup_dir, exist_ok=True)
        os.makedirs(self.log_dir, exist_ok=True)

    def initialize_browser(self):
        """初始化浏览器实例"""
        self.driver = init_chrome_browser(
            chrome_path=chrome_path,
            driver_path=driver_path,
            # download_dir=self.download_dir,
            detach=True
        )
        return self.driver

    def login(self, url, username, password):
        """登录系统"""
        self.driver.get(url)
        self.driver.maximize_window()

        # 处理安全警告
        self.driver.find_element(By.XPATH, "/html/body/div/div[2]/button[3]").click()  # 高级
        self.driver.find_element(By.XPATH, "/html/body/div/div[3]/p[2]/a").click()  # 进入

        # 输入凭据
        self.driver.find_element(
            By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[1]/div/input"
        ).send_keys(username)

        self.driver.find_element(
            By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[2]/div/input"
        ).send_keys(password)

        self.driver.find_element(
            By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[5]/div/button"
        ).click()

    def navigate_to_database(self):
        """导航到数据库页面"""
        element = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH, "/html/body/section/aside/section/div[2]/div/div/div[1]/div/ul/li[4]/a/span")
            )
        )
        element.click()

    def perform_backup(self):
        """执行备份操作"""
        element = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "/html/body/section/section/section/div[1]/div/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[3]/table/tbody/tr[2]/td[6]/div/div/div/span[1]")
            )
        )
        element.click()

    def download_backup(self):
        """下载备份文件"""
        element = WebDriverWait(self.driver, 15).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "/html/body/div[2]/div/div[2]/div[2]/div/div[1]/div/div[2]/div[1]/div/div[2]/div/div[4]/div[2]/table/tbody/tr[1]/td[7]/div/div/div/span[2]")
            )
        )
        element.click()
        return element.text == "下载"  # 验证按钮文本

    def backup_latest_file(self):
        """备份下载的最新文件"""
        files = [
            (os.path.getmtime(f.path), f.name, f.path)
            for f in os.scandir(self.download_dir)
            if f.is_file()
        ]

        if not files:
            raise FileNotFoundError("No files found in download directory")

        files.sort(reverse=True)
        _, filename, filepath = files[0]

        time_str = datetime.now().strftime('%Y_%m_%d_%H%M')
        backup_folder = os.path.join(self.backup_dir, f"{time_str}_backup")
        os.makedirs(backup_folder, exist_ok=True)

        shutil.copy2(filepath, os.path.join(backup_folder, filename))
        return backup_folder

    def log(self, message):
        """记录日志"""
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(f"{datetime.now().isoformat()} - {message}\n")

    def cleanup(self):
        """清理资源"""
        if self.driver:
            self.driver.quit()

